import torch
import torch.nn as nn
from functools import partial
import math

def drop_path(x, drop_prob: float = 0., training: bool = False):
    """
    Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
    This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
    the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
    See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
    changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
    'survival rate' as the argument.
    """
    if drop_prob == 0. or not training:
        return x
    keep_prob = 1 - drop_prob
    shape = (x.shape[0],) + (1,) * (x.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
    random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
    random_tensor.floor_()  # binarize
    output = x.div(keep_prob) * random_tensor
    return output

class DropPath(nn.Module):
    """
    Drop paths (Stochastic Depth) per sample  (when applied in main path of residual blocks).
    """

    def __init__(self, drop_prob=None):
        super(DropPath, self).__init__()
        self.drop_prob = drop_prob

    def forward(self, x):
        return drop_path(x, self.drop_prob, self.training)

class PatchEmbed(nn.Module):
    """
    B C H W to Patch Embedding
    Args:
    feature_scale: 输入特征尺度, 例如 1/4 即为 4
    input_feat_dim: 输入特征通道数
    patch_size: 生成及处理的 patch size 大小，例如 patch size = 16, 其尺度为 1/16
    norm_layer: 归一化层
    """

    def __init__(self, feature_scale, input_feat_dim=256, patch_size=16, norm_layer=None):
        super().__init__()
        # 计算下采样倍数，例如输入为 1/4， 要处理的是 1/16， 则下采样倍数是 4
        self.downsample_ratio = patch_size // feature_scale
        # grid_scale = (self.grid_scale, self.grid_scale) #4

        # 下采样的次数，例如输入为 1/4， 要处理的是 1/16， 则下采样倍数是 4，下采样次数为 2
        time = int(self.downsample_ratio // 2)  # 下采样的次数，每次下采样为原来的 1/2

        # # 下采样
        # self.maxp = nn.ModuleList()
        # for i in range(time):
        #     maxp = nn.Sequential(
        #             nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
        #             # 下采样一次，通道数增大一倍
        #             nn.Conv2d(input_feat_dim * (2 ** i), input_feat_dim * (2 ** (i + 1)), kernel_size=1, stride=1),
        #             nn.BatchNorm2d(input_feat_dim * (2 ** (i + 1))),
        #             nn.ReLU(inplace=True),
        #     )
        #     self.maxp.append(maxp)


        # # 混合下采样拼接
        # # MaxPooling下采样层组
        # self.maxp = nn.ModuleList()
        #
        # # 卷积下采样层组
        # self.conv = nn.ModuleList()
        #
        # # 融合组
        # self.fuse = nn.ModuleList()
        #
        # for i in range(time):
        #     maxp = nn.Sequential(
        #         nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
        #         # 下采样一次，通道数增加保持不变
        #         nn.Conv2d(input_feat_dim * (2 ** i), input_feat_dim * (2 ** i), kernel_size=1, stride=1),
        #         nn.BatchNorm2d(input_feat_dim * (2 ** i)),
        #     )
        #     self.maxp.append(maxp)
        #
        #     conv = nn.Sequential(
        #         # 下采样一次，通道数保持不变
        #         nn.Conv2d(input_feat_dim * (2 ** i), input_feat_dim * (2 ** i), kernel_size=3, stride=2, padding=1),
        #         nn.BatchNorm2d(input_feat_dim * (2 ** i)),
        #     )
        #     self.conv.append(conv)
        #
        #     # 下采样一次， 通道数增大一倍
        #     fuse = nn.Sequential(
        #         # 将融合后 2倍通道数 卷积为 2倍通道数
        #         nn.Conv2d(input_feat_dim * (2 ** (i + 1)), input_feat_dim * (2 ** (i + 1)), kernel_size=1, stride=1),
        #         nn.BatchNorm2d(input_feat_dim * (2 ** (i + 1))),
        #         nn.ReLU(inplace=True),
        #     )
        #     self.fuse.append(fuse)


        # 混合下采样相加
        # MaxPooling下采样层组
        self.maxp = nn.ModuleList()

        # 卷积下采样层组
        self.conv = nn.ModuleList()

        for i in range(time):
            maxp = nn.Sequential(
                nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
                # 下采样一次，通道数增大一倍
                nn.Conv2d(input_feat_dim * (2 ** i), input_feat_dim * (2 ** (i + 1)), kernel_size=1, stride=1),
                nn.BatchNorm2d(input_feat_dim * (2 ** (i + 1))),
                nn.ReLU(inplace=True),
            )
            self.maxp.append(maxp)

            conv = nn.Sequential(
                # 下采样一次，通道数增大一倍
                nn.Conv2d(input_feat_dim * (2 ** i), input_feat_dim * (2 ** (i + 1)), kernel_size=3, stride=2, padding=1),
                nn.BatchNorm2d(input_feat_dim * (2 ** (i + 1))),
                nn.ReLU(inplace=True),
            )
            self.conv.append(conv)

        # 生成并处理的特征图的通道数, 即 输入通道数 * 2^(下采样次数)
        self.channel_num = input_feat_dim * (2 ** time)
        # 若没有传入 norm_layer，则使用 nn.Identity() 即不做任何处理
        self.norm = norm_layer(self.channel_num) if norm_layer else nn.Identity()

    def forward(self, x):
        # flatten: [B, C, H, W] -> [B, C, HW]
        # transpose: [B, C, HW] -> [B, HW, C]
        for i in range(len(self.maxp)):
            # # 下采样
            # x = self.maxp[i](x)

            # # 混合下采样拼接
            # x = torch.cat((self.maxp[i](x), self.conv[i](x)), dim=1)
            # x = self.fuse[i](x)

            # 混合下采样相加
            x = self.maxp[i](x) + self.conv[i](x)

        x = x.flatten(2).transpose(1, 2)
        x = self.norm(x)
        return x

class Attention(nn.Module):
    def __init__(self,
                 dim,                   # 输入 token 的 dimension， 即 B x HW x C 的 C
                 num_heads=8,
                 qkv_bias=False,
                 qk_scale=None,
                 attn_drop_ratio=0.,
                 proj_drop_ratio=0.):
        super(Attention, self).__init__()
        self.num_heads = num_heads
        head_dim = dim // num_heads     # 每一个 head 的 dimension
        self.scale = qk_scale or head_dim ** -0.5   # 即 qk点积相乘的分母项，可传入数值
        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
        self.attn_drop = nn.Dropout(attn_drop_ratio)
        self.proj = nn.Linear(dim, dim)             # 处理 concat head 之后的 token维度
        self.proj_drop = nn.Dropout(proj_drop_ratio)

    def forward(self, x):
        # [batch_size, num_patches, total_embed_dim]
        B, N, C = x.shape

        # qkv(): -> [batch_size, num_patches, 3 * total_embed_dim]
        # reshape: -> [batch_size, num_patches, 3, num_heads, embed_dim_per_head]
        # permute: -> [3, batch_size, num_heads, num_patches, embed_dim_per_head]
        qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
        # [batch_size, num_heads, num_patches, embed_dim_per_head]
        q, k, v = qkv[0], qkv[1], qkv[2]

        # transpose: -> [batch_size, num_heads, embed_dim_per_head, num_patches]
        # @: multiply -> [batch_size, num_heads, num_patches, num_patches]
        # @: 矩阵乘法，只针对最后两个维度操作
        attn = (q @ k.transpose(-2, -1)) * self.scale
        attn = attn.softmax(dim=-1)     # 将点积注意力结果每一行进行 softmax 处理
        attn = self.attn_drop(attn)

        # @: multiply -> [batch_size, num_heads, num_patches, embed_dim_per_head]
        # transpose: -> [batch_size, num_patches, num_heads, embed_dim_per_head]
        # reshape: -> [batch_size, num_patches, total_embed_dim]
        x = (attn @ v).transpose(1, 2).reshape(B, N, C)
        x = self.proj(x)
        x = self.proj_drop(x)
        return x

class Mlp(nn.Module):
    """
    MLP as used in Vision Transformer, MLP-Mixer and related networks
    """
    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
        super().__init__()
        out_features = out_features or in_features      # out_freature 默认为 in_features
        hidden_features = hidden_features or in_features   # hidden_features 一般为 in_features 的两倍， 默认为 in_features

        self.fc1 = nn.Linear(in_features, hidden_features)
        self.act = act_layer()
        self.drop1 = nn.Dropout(drop)
        self.fc2 = nn.Linear(hidden_features, out_features)
        self.drop2 = nn.Dropout(drop)

    def forward(self, x):
        x = self.fc1(x)
        x = self.act(x)
        x = self.drop1(x)
        x = self.fc2(x)
        x = self.drop2(x)
        return x

class Block(nn.Module):
    def __init__(self,
                 dim,           # token 的 dimension
                 num_heads,
                 mlp_ratio=4.,  # mlp 隐藏层维度数与输入层维度数的倍数
                 qkv_bias=False,
                 qk_scale=None,
                 drop_ratio=0.,     # concat multi head
                 attn_drop_ratio=0.,    # softmax(点积注意力)
                 drop_path_ratio=0.,    # Block 中 自注意力和 MLP 之后
                 act_layer=nn.GELU,
                 norm_layer=nn.LayerNorm):
        super(Block, self).__init__()
        self.norm1 = norm_layer(dim)
        self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
                              attn_drop_ratio=attn_drop_ratio, proj_drop_ratio=drop_ratio)
        # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
        self.drop_path = DropPath(drop_path_ratio) if drop_path_ratio > 0. else nn.Identity()
        self.norm2 = norm_layer(dim)
        mlp_hidden_dim = int(mlp_ratio * dim)
        self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop_ratio)

    def forward(self, x):
        x = x + self.drop_path(self.attn(self.norm1(x)))
        x = x + self.drop_path(self.mlp(self.norm2(x)))
        return x

class PositionEmbeddingSine(nn.Module):
    """
    This is a more standard version of the position embedding, very similar to the one
    used by the Attention is all you need paper, generalized to work on images.
    """

    def __init__(self, temperature=10000, normalize=False, scale=None):
        super().__init__()
        self.temperatures = temperature
        self.normalzie = normalize
        if scale is not None and normalize is False:
            raise ValueError("normalize should be True if scale is passed")
        if scale is None:
            scale = 2 * math.pi
        self.scale = scale

    def forward(self, x):
        # 输入维度方向的累积和
        # 1 x N
        not_mask = torch.ones(x.shape[0], x.shape[1]).to(x.device)
        embed = not_mask.cumsum(1, dtype=torch.float32)
        if self.normalzie:
            eps = 1e-6
            embed = embed / (embed[:, -1:] + eps) * self.scale

        # dim维向量[0,1,2...dim-1]
        dim_t = torch.arange(x.shape[2], dtype=torch.float32, device=x.device)
        # 10000^(2i/dim)
        dim_t = self.temperatures ** (2 * (dim_t // 2) / x.shape[2])

        # b x N x dim/2
        pos = embed[:, :, None] / dim_t

        # b x N x dim
        pos = torch.stack((pos[:, :, 0::2].sin(), pos[:, :, 1::2].cos()), dim=3).flatten(2)
        # b x dim x N
        #pos = pos.permute(0, 2, 1)
        return pos

class PositionEmbeddingSineTwoDimension(nn.Module):
    """
        PositionEmbeddingSine for two dimension feature map
    """

    def __init__(self, temperature=10000, normalize=False, scale=None):
        super().__init__()
        self.temperature = temperature
        self.normalize = normalize
        if scale is not None and normalize is False:
            raise ValueError("normalize should be True if scale is passed")
        if scale is None:
            scale = 2 * math.pi
        self.scale = scale

    # x -- B C H W
    def forward(self, x):
        # B H W
        not_mask = torch.ones(x.shape[0], x.shape[2], x.shape[3]).to(x.device)
        y_embed = not_mask.cumsum(1, dtype=torch.float32)
        x_embed = not_mask.cumsum(2, dtype=torch.float32)
        if self.normalize:
            eps = 1e-6
            y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
            x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale

        # dim维向量[0,1,2...dim-1]
        dim_t = torch.arange(x.shape[1] // 2, dtype=torch.float32, device=x.device)
        # 10000^(2i/dim)
        dim_t = self.temperature ** (2 * (dim_t // 2) / x.shape[1])

        # B H W dim/2
        pos_x = x_embed[:, :, :, None] / dim_t
        pos_y = y_embed[:, :, :, None] / dim_t
        # B H W dim
        pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
        pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
        # B 2dim H W
        pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
        return pos

# 每个尺度特征图的通道数需要被 attention 模块中的 head 数量整除
class VisionAttention(nn.Module):
    def __init__(self,feature_scale=4,input_feat_dim=256,patch_size=16,
                 depth=6,num_heads=8,mlp_ratio=2.0,qkv_bias=True,qk_scale=None,
                 drop_ratio=0.,attn_drop_ratio=0.,drop_path_ratio=0.,embed_layer=PatchEmbed,
                 pos_layer=PositionEmbeddingSineTwoDimension,norm_layer=None,act_layer=None):
        """
        Args:
            feature_scale: 输入特征尺度, 例如 1/4 即为 4
            input_feat_dim (int): 输入特征通道数
            patch_size (int): 生成及处理的 patch size 大小，例如 patch size = 16, 其尺度为 1/16
            depth (int): depth of transformer 即 Block的个数
            num_heads (int): number of attention heads
            mlp_ratio (float): ratio of mlp hidden dim to embedding dim
            qkv_bias (bool): enable bias for qkv if True
            qk_scale (float): override default qk scale of head_dim ** -0.5 if set
            drop_ratio (float): dropout rate
            attn_drop_ratio (float): attention dropout rate
            drop_path_ratio (float): stochastic depth rate
            pos_layer: 位置编码
            embed_layer (nn.Module): patch embedding layer
            norm_layer: (nn.Module): normalization layer
            act_layer: (nn.Module): Activation layer.
        """
        super(VisionAttention,self).__init__()
        self.patch_size=patch_size
        self.feature_scale=feature_scale

        # 默认为 nn.LayerNorm, partial 传入默认参数 eps
        norm_layer = norm_layer or partial(nn.LayerNorm,eps=1e-6)
        # 默认为 nn.GELU
        act_layer = act_layer or nn.GELU

        self.patch_embed = embed_layer(feature_scale=self.feature_scale,input_feat_dim=input_feat_dim,patch_size=self.patch_size)
        embed_dim = self.patch_embed.channel_num                    # 处理特征的通道数
        self.downsample_ratio = self.patch_embed.downsample_ratio   # 输入特征下采样倍数


        # 参数化位置编码
        # self.h = 320 // 4
        # self.w = 320 // 4
        # num_patches = (self.h // self.downsample_ratio) * (self.w // self.downsample_ratio)
        # self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
        self.pos_embed = pos_layer()
        # 加上位置编码后的 drop out 层
        self.pos_drop = nn.Dropout(p=drop_ratio)

        dpr = [x.item() for x in torch.linspace(0,drop_path_ratio,depth)]       # stochastic depth decay rule
        self.blocks = nn.Sequential(*[
            Block(dim=embed_dim,num_heads=num_heads,mlp_ratio=mlp_ratio,qkv_bias=qkv_bias,qk_scale=qk_scale,
                  drop_ratio=drop_ratio,attn_drop_ratio=attn_drop_ratio,drop_path_ratio=dpr[i],
                  norm_layer=norm_layer,act_layer=act_layer)
            for i in range(depth)
        ])

        # Transformer Encoder Block 之后的 Layer Norm 层
        self.norm = norm_layer(embed_dim)
        self.apply(_init_vit_weights)

    def forward(self,x):
        B,C,H,W=x.shape
        #[B,C,H,W] -> [B,N,d]
        x=self.patch_embed(x)   #[B,N,d]

        B, N, C = x.shape
        H1 = int(H // self.downsample_ratio)
        W1 = int(W // self.downsample_ratio)

        # 二维余弦位置编码
        y = x.reshape(B, C, H1, W1)
        x = self.pos_drop(self.pos_embed(y).flatten(2).transpose(1, 2) + x)

        # 一维余弦位置编码
        # x=self.pos_drop(self.pos_embed(x) + x)

        # 参数化绝对位置编码
        # x = self.pos_drop(self.pos_embed + x)

        x=self.blocks(x)
        #B x HW X C
        x=self.norm(x)

        x = x.view(B, C, H1, W1)

        return x

def _init_vit_weights(m):
    """
        ViT weight initialization
        :param m: module
    """
    if isinstance(m, nn.Linear):
        nn.init.trunc_normal_(m.weight, std=.01)
        if m.bias is not None:
            nn.init.zeros_(m.bias)
    elif isinstance(m, nn.Conv2d):
        nn.init.kaiming_normal_(m.weight, mode="fan_out")
        if m.bias is not None:
            nn.init.zeros_(m.bias)
    elif isinstance(m, nn.LayerNorm):
        nn.init.zeros_(m.bias)
        nn.init.ones_(m.weight)